package com.codeanalysissys.backend.utils;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

@Component
public class CookieUtil {
    /**
     * 获取请求中名为`key`的cookie
     * @param request http请求
     * @param key cookie名
     * @return
     */
    public Cookie getUserCookie(HttpServletRequest request, String key) {
        Cookie[] cookies = request.getCookies();
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if (cookie.getName().equals(key)) {
                    return cookie;
                }
            }
        }
        return null;
    }


    /**
     * 生成一个基于当前时间的毫秒级时间戳的UUID
     * @return UUID
     */
    public String generateUUID() {
        // 获取当前时间的毫秒级时间戳
        long currentTimeMillis = System.currentTimeMillis();

        // 使用时间戳创建 UUID
        UUID timeBasedUUID = new UUID(currentTimeMillis, 0);

        return timeBasedUUID.toString();
    }


    /**
     * 生成SHA256加密算法生成的cookie
     * @param key cookie名
     * @return
     */
    public String generateSHA256Cookie(String key) {
        MessageDigest md;
        try {
            // get SHA-256 generator
            md = MessageDigest.getInstance("SHA-256");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            return null;
        }
        byte[] shaBytes = md.digest(key.getBytes());

        // Convert the byte array to a hexadecimal string
        StringBuilder sb = new StringBuilder();
        for (byte shaByte : shaBytes) {
            sb.append(Integer.toString((shaByte & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }
}
